<script setup>
import { phoneCaptcha, byPhone, byMail } from '@/api/user'
import { PHONE_REGEXP, EMAIL_REGEXP } from '@/utils/regExp'

const props = defineProps({
  operation: {
    type: String,
    default: 'Login'
  },
  userName: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['validate'])

const sendData = reactive({
  isSendedMessage: false,
  count: 60,
  interval: null,
  loading: false
})
const validateFirst = () => {
  return new Promise((resolve, rejected) => {
    const { operation, userName } = props
    const isEmail = operation === 'FindByEmail'
    if (!userName) {
      resolve(false)
    }
    if (isEmail) {
      resolve(EMAIL_REGEXP.test(userName))
    } else {
      resolve(PHONE_REGEXP.test(userName))
    }
  })
}
// 获取验证码
const sendMessage = async () => {
  const { operation, userName } = props
  const isPass = await validateFirst();
  if (isPass) {
    sendData.loading = true
    if (operation === 'Login') {
      await phoneCaptcha(userName)
    }
    if (operation === 'FindByPhone') {
      await byPhone(userName)
    }
    if (operation === 'FindByEmail') {
      await byMail(userName)
    }
    sendData.isSendedMessage = true
    disCount(60)
    sendData.loading = false
  } else {
    emit('validate')
  }
}
const disCount = (val) => {
  sendData.count = val
  sendData.interval = setInterval(function () {
    sendData.count--
  }, 1000)
}

watch(
  () => sendData.count,
  (newValue, oldValue) => {
    if (newValue <= 0) {
      sendData.isSendedMessage = false
      clearInterval(sendData.interval)
      sendData.count = 60
    }
  }
)

onBeforeUnmount(() => {
  clearInterval(sendData.interval)
  sendData.interval = null
})
</script>

<template>
  <div>
    <div
      v-if="!sendData.isSendedMessage"
      @click="sendMessage"
      class="w-24 h-8 bg-indigo-400 cursor-pointer rounded-lg text-white text-center ml-2 leading-8"
      v-loading="sendData.loading"
    >
      发送验证码
    </div>
    <div v-else class="w-24 h-8 bg-gray-400 cursor-not-allowed rounded-lg text-white text-center ml-2 leading-8">
      已发送 {{ sendData.count }} 秒
    </div>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-loading-spinner .circular) {
  width: 22px;
  height: 22px;
}
:deep(.el-loading-spinner) {
  top: 62%;
}
</style>
